import os
import json
import pymysql


def save_message_to_db(node_uuid, receive_data_time, sender_number, message_content):
    host = os.environ.get("DB_HOST")
    port = int(os.environ.get("DB_PORT"))
    user = os.environ.get("DB_USERNAME")
    password = os.environ.get("DB_PASSWORD")
    database = os.environ.get("DB_DATABASE")

    dbc = pymysql.connect(host=host, port=port, user=user, password=password, database=database)

    with dbc:
        with dbc.cursor() as cursor:
            sql = "INSERT INTO `message` (`node_uuid`, `receive_date_time`, `sender_number`, `message_content`)" \
                  " VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (node_uuid, receive_data_time, sender_number, message_content))
        dbc.commit()
    return {
                "isBase64Encoded": False,
                "statusCode": 200,
                "headers": {"Content-Type": "application/json; charset=utf-8"},
                "body": json.dumps({
                    "message": "ok"
                })
            }


def get_message_from_db():
    host = os.environ.get("DB_HOST")
    port = int(os.environ.get("DB_PORT"))
    user = os.environ.get("DB_USERNAME")
    password = os.environ.get("DB_PASSWORD")
    database = os.environ.get("DB_DATABASE")

    dbc = pymysql.connect(host=host, port=port, user=user, password=password, database=database)

    with dbc:
        with dbc.cursor() as cursor:
            sql = "SELECT * FROM `message` ORDER BY `id` DESC"
            cursor.execute(sql)
            results = cursor.fetchall()

            data = []

            for item in results:
                data.append({
                    "id": item[0],
                    "uuid": item[1],
                    "dateTime": item[2].strftime('%Y-%m-%d %H:%M:%S'),
                    "senderNumber": item[3],
                    "messageContent": item[4],
                    "haveRead": item[5]
                })

            return {
                "isBase64Encoded": False,
                "statusCode": 200,
                "headers": {"Content-Type": "application/json; charset=utf-8"},
                "body": json.dumps(data)
            }


def main_handler(event, context):
    method = event['httpMethod']
    if method == "GET":
        return get_message_from_db()
    elif method == "POST":
        query_body_string = event['body']
        query_object = json.loads(query_body_string)

        return save_message_to_db(query_object['nodeUUID'], query_object['dateTime'], query_object['senderNumber'],
                                  query_object['messageContent'])

    return {
        "isBase64Encoded": False,
        "statusCode": 400,
        "headers": {"Content-Type": "application/json; charset=utf-8"},
        "body": "UNKNOWN HTTP METHOD"
    }


if __name__ == '__main__':
    get_message_from_db()
